#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  source.py
#  description

#  Created by zhouzongli633 on 2020/7/17 1:13 下午.
#  Copyright ©Intellectus All rights reserved.
import json
from datetime import datetime

from Common.decorators import check_param, check_body, method
from Common.decorators import check_token
from Common.logger import app_log
from Common.response import resp
from EducationContent.models import Source, EducationFeeds


@check_token()
@check_body(['name', 'logo', 'target'])
def source_create(request):
    try:
        date = datetime.utcnow()
        post_param = json.loads(request.body)
        record = Source(
            name=post_param['name'],
            logo=post_param['logo'],
            target=post_param['target'],
            created_at=date,
            updated_at=date
        )
        record.save()

        ret = record.source_to_json()

        return resp(0, ret)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_body(['id'])
def source_delete(request):
    try:
        body_json = json.loads(request.body)
        source_id = body_json['id']
        record = Source.objects.filter(id=source_id).first()
        if record:
            record.delete()
        else:
            return resp(4001)

        return resp(0, record.source_to_json())

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_body(['id', 'name', 'logo', 'target'])
def source_update(request):
    try:
        date = datetime.utcnow()
        post_param = json.loads(request.body)
        record_current = Source.objects.get(id=post_param['id'])
        logo_old = record_current.logo
        if not record_current:
            return resp(4001)

        record_current.name = post_param['name']
        record_current.logo = post_param['logo']
        record_current.target = post_param['target'] if 'target' in post_param else ""
        record_current.updated_at = date
        record_current.save()

        EducationFeeds.objects.filter(source=logo_old).update(source=post_param['logo'], updated_at=date)

        return resp(0, record_current.source_to_json())
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
def source_detail(request):
    try:
        source_id = request.GET.get('id')

        it = Source.objects.get(id=source_id)
        if not it:
            return resp(4001)
        feed_json = it.source_to_json()

        return resp(0, feed_json)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_param(['hospital_id'])
@method(["GET"])
def source_list(request):
    try:
        data = {}
        hospital_id = request.GET.get('hospital_id')

        source_list = Source.objects.all()
        if not source_list or len(source_list) == 0:
            return resp(4001)
        list = []
        if hospital_id == '*':
            for it in source_list:
                list.append(it.source_to_json())
        else:
            for it in source_list:
                if hospital_id in it.target.split(',') or it.target == '*':
                    list.append(it.source_to_json())
        data["source_list"] = list
        return resp(0, data)

    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))
